import React, { useState, useMemo, useEffect } from 'react'
import { useOutletContext } from 'react-router-dom';
import { Table, Input, Button, MessagePlugin, Dialog, Link } from 'tdesign-react';

const FixedTopic = () => {
  const { page,pagesize,setpage,setpagesize,totalTopicLength,score, setScore, data1, setData, SelectedRowKeys, setSelectedRowKeys, questions } = useOutletContext();
  // console.log(options);
  const [selected,setSelected] = useState([])
  useEffect(() => {
    let arr = questions.filter(item => {
      return SelectedRowKeys.includes(item._id)
    },[])
    setData(arr)
  }, [questions, SelectedRowKeys])
  const editableCellState = (cellParams) =>
    // 第一行不允许编辑
    cellParams.rowIndex !== '';
  const columns = useMemo(
    () => [
      {
        colKey: 'row-select',
        type: 'multiple',
      },
      {
        title: '试题类型',
        colKey: 'cate',
        align: 'center',
        cell: ({ row }) => {
          switch (row.cate) {
            case 1:
              return '单选题'
            case 2:
              return '多选题'

            case 3:
              return '判断题'

            case 4:
              return '简答题'

            default:
              return '未知'

          }
        }
      },
      {
        title: '题干',
        colKey: 'title',
        width: 280,
      },
      {
        title: '正确选项',
        colKey: 'options',
        cell: ({ row }) => {
          return row.options.filter(item => item.isRight).map(item => item.title.charAt(0))
        }
      },
      {
        title: '选项内容',
        colKey: Date.now(),
        cell: ({ row }) => {
          return row.options.filter(item => item.isRight).map(item => item.title.split('.')[1])
        }
      },
      {
        title: '难度',
        colKey: 'difficulty',
        align: 'center',
        cell: ({ row }) => {
          switch (row.difficulty) {
            case 1:
              return '简单';
            case 2:
              return '中等';
            case 3:
              return '困难';
            default:
              return '未知';
          }
        }
      },
      {
        title: '分数',
        colKey: 'score',
        align: 'center',
      },
      {
        title: '操作',
        colKey: 'operation',
        cell: ({ row }) => (
          <div className="tdesign-table-demo__table-operations">
            <Link hover="color" onClick={() => remove(row._id)}>删除</Link>
          </div>
        ),
      }
    ],
    [data1],
  );
  const columnQuestions = [
    {
      colKey: 'row-select',
      type: 'multiple',
    },
    {
      title: '试题类型',
      colKey: 'cate',
      align: 'center',
      cell: ({ row }) => {
        switch (row.cate) {
          case 1:
            return '单选题'
          case 2:
            return '多选题'
          case 3:
            return '判断题'
          case 4:
            return '简答题'
          default:
            return '未知'
        }
      }
    },
    {
      title: '题干',
      colKey: 'title',
      width: 280,
    },
    {
      title: '正确选项',
      colKey: 'options',
      cell: ({ row }) => {
        return row.options.filter(item => item.isRight).map(item => item.title.charAt(0))
      }
    },
    {
      title: '选项内容',
      colKey: Date.now(),
      width: 200,
      cell: ({ row }) => {
        return row.options.filter(item => item.isRight).map(item => item.title.split('.')[1])
      }
    },
    {
      title: '解析',
      colKey: 'answer',
      width: 200,
      align: 'center',
      cell: ({ row }) => (
        <div style={{ width: '100%', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', }}>
          {row.answer}
        </div>
      )
    },
    {
      title: '难度',
      colKey: 'difficulty',
      align: 'center',
      cell: ({ row }) => {
        switch (row.difficulty) {
          case 1:
            return '简单';
          case 2:
            return '中等';
          case 3:
            return '困难';
          default:
            return '未知';
        }
      }
    },
  ];
  const [visible, setVisible] = useState(false);
  const [visible1, setVisible1] = useState(false);

  function rehandleChange(pageInfo) {
    const { current, pageSize } = pageInfo;
    setpage(current);
    setpagesize(pageSize);

  }
  const handleClick = () => {
    setVisible(true);
  };
  const handleClick1 = () => {
    if (SelectedRowKeys.length === 0) {
      MessagePlugin.error('请添加题目');
      return
    } else {
      setVisible1(true);
    }
  }
  const onConfirm = (context) => {
    setVisible(false);
  };
  const handleClose = (context) => {
    setSelectedRowKeys([]);
    setVisible(false);
  };
  const onConfirm1 = (context) => {
    setVisible1(false);
    let validate  = /^\d{1,2}$/
    if(!validate.test(score)){
      MessagePlugin.error('请输入1-99的整数');
      return
    }
    setAllScore(score);
    MessagePlugin.success('批量设置成功');
  };
  const handleClose1 = (context) => {
    setScore('');
    setVisible1(false);
  };
  const onSelectChange = (value, { selectedRowData }) => {
    setSelectedRowKeys(value);
  };
  const remove = (_id) => {
    setData(v => v.filter(item => item._id !== _id));
    setSelectedRowKeys(v => v.filter(item => item !== _id))
  }
  const setAllScore = () => {
    setData(v => v.map(item => ({ ...item, score })))
  }
  const removeFromList = ()=>{
    setSelectedRowKeys(v => v.filter(item => selected.includes(item._id)));
    setData(v => v.filter(item => !selected.includes(item._id)));
  }
  return (
    <div id='fixedTopic'>
      <div className='header'>
        <Button onClick={handleClick}>添加试题</Button>
        <Button theme='warning' onClick={handleClick1}>批量设置分数</Button>
        <Button theme='default' disabled={selected.length===0} onClick={removeFromList}>批量移除</Button>
      </div>
      <Dialog
        header="添加试题"
        width={1100}
        visible={visible}
        confirmOnEnter
        onClose={handleClose}
        onConfirm={onConfirm}
      >
        <Table rowKey="_id"
          columns={columnQuestions}
          data={questions}
          stripe={true}
          resizable={true}
          pagination={{
            current:page,
            pageSize:pagesize,
            total:totalTopicLength,
            defaultPageSize:pagesize,
            pageSizeOptions:[2,6,8,10],
            showJumper: true,
            onChange(pageInfo) {
              console.log(pageInfo, 'onChange pageInfo');
              rehandleChange(pageInfo);
            },
          }}
          selectedRowKeys={SelectedRowKeys}
          onSelectChange={onSelectChange}
        />
      </Dialog>
      <Dialog
        header="批量设置分数"
        visible={visible1}
        confirmOnEnter
        onClose={handleClose1}
        onConfirm={onConfirm1}
      >
        <Input label='分值：' value={score} onChange={(e) => setScore(e)}></Input>
      </Dialog>
      <Table rowKey="_id" 
      columns={columns} 
      data={data1} 
      editableCellState={editableCellState} 
      selectedRowKeys={selected}
      onSelectChange={(e)=>setSelected(e)}
      bordered  />
    </div>
  )
}

export default FixedTopic
